<?php

namespace app\admin\controller\column;

use app\common\controller\Backend;
use app\admin\controller\ColumnHelper;
use fast\Tree;
use Exception;

/**
 * 
 *
 * @icon fa fa-file
 */
class Column extends Backend
{

    /**
     * Column模型对象
     */
    protected $model = null;
    protected $shopid;
    protected $noNeedRight = ['lists', 'getcolumns'];
    protected $noNeedLogin = ['lists', 'getcolumns'];


    public function _initialize()
    {
        parent::_initialize();
        $this->shopid = false;
        $this->model = model('Column');
    }

    /**
     * 输出JSON响应
     * @param int $code 状态码 1=成功 0=失败
     * @param string $msg 消息
     * @param array $data 数据
     * @param bool $refresh 是否刷新
     */


    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);

        // 获取当前用户组信息
        $user = $this->auth->getUserInfo();
        $usergroup = db('auth_group_access')
            ->alias('access')
            ->join('auth_group group', 'group.id=access.group_id')
            ->where('access.uid', $this->auth->id)
            ->find();

        // 调试信息
        \think\Log::write('User ID: ' . $this->auth->id, 'debug');
        \think\Log::write('User Group Info: ' . json_encode($usergroup), 'debug');

        // 检查用户是否有编辑type字段的权限
        $userGroupId = $user['group_id'] ?? 0;
        $canEditType = in_array($userGroupId, [1, 2]); // 超级管理员或城市管理员

        // 传递到前端
        $admin_config = [
            'group' => [
                'name' => $usergroup ? $usergroup['name'] : '',
                'id' => $userGroupId
            ],
            'id' => $user['id'], // 添加用户ID
            'canEditType' => $canEditType
        ];

        // 调试信息
        \think\Log::write('Admin Config: ' . json_encode($admin_config), 'debug');

        $this->assignconfig('admin', $admin_config);
        $this->assignconfig('canEditType', $canEditType);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 获取城市和学校过滤参数
            $city_id = $this->request->get("city_id");
            $school_id = $this->request->get("school_id");

            $totalQuery = $this->model->where($where);
            // 城市过滤：若传入city_id，则按传入过滤；否则若是城市管理员(group_id=2)则按session城市
            if (!empty($city_id)) {
                $totalQuery = $totalQuery->where("city_id", "=", $city_id);
            } else if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 2) {
                $totalQuery = $totalQuery->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }
            // 学校过滤：若传入school_id，则按学校过滤；若学校管理员(group_id=3)可根据自身学校再加限制
            if (!empty($school_id)) {
                $totalQuery = $totalQuery->where("school_id", "=", $school_id);
            }
            if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 3) {
                $totalQuery = $totalQuery->where("school_id", "=", $_SESSION['think']['admin']['school_id']);
            }
            $total = $totalQuery->order($sort, $order)->count();

            $listQuery = $this->model->where($where);
            if (!empty($city_id)) {
                $listQuery = $listQuery->where("city_id", "=", $city_id);
            } else if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 2) {
                $listQuery = $listQuery->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            }
            if (!empty($school_id)) {
                $listQuery = $listQuery->where("school_id", "=", $school_id);
            }
            if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 3) {
                $listQuery = $listQuery->where("school_id", "=", $_SESSION['think']['admin']['school_id']);
            }

            $list = $listQuery
                //->order("weigh desc")
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            //$this->model->getLastSql();
            $list = collection($list)->toArray();
            for ($i = 0; $i < count($list); $i++) {
                //$list[$i]['pid']=$this->model->getPidTextAttr($list[$i]['pid'],$list[$i]);
                $list[$i]['name'] = $list[$i]['column'];
                $list[$i]['city_id'] = model("Cityarea")->getCity_idTextAttr($list[$i]['city_id'], $list[$i]);
                $list[$i]['school_id'] = model("School")->getSchool_idTextAttr($list[$i]['school_id'], $list[$i]);
                $list[$i]['type'] = $list[$i]['type'] == 1 ? "是" : "否";
                // 使用模型的访问器方法处理diff字段
                //$list[$i]['diff'] = $this->model->getDiffTextAttr($list[$i]['diff'] ?? 0, $list[$i]);
                $list[$i]['status'] = $list[$i]['status'] == 1 ? "生效中" : "失效中";
            }

            // 构建树形结构
            $tree = Tree::instance();
            $tree->init($list, 'pid');
            $list = $tree->getTreeList($tree->getTreeArray(0), 'name');

            // 为树形结构添加层级符号
            foreach ($list as &$item) {
                $level = substr_count($item['name'], chr(8));
                if ($level > 0) {
                    $prefix = str_repeat('│   ', $level - 1);
                    $symbol = '├── ';
                    // 检查是否是最后一个子节点
                    $item['name'] = $prefix . $symbol . trim(str_replace(chr(8), '', $item['name']));
                }
            }

            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        $user = $this->auth->getUserInfo();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }

                    // 权限检查：只有超级管理员(group_id=1)或城市管理员(group_id=2)才能设置type字段
                    if (isset($params['type']) && $params['type'] == 1) {
                        $userGroupId = $user['group_id'] ?? 0;
                        if (!in_array($userGroupId, [1, 2])) {
                            $this->error('您没有权限设置固定栏目，只有超级管理员或城市管理员才能操作');
                        }
                    }

                    $params['update_time'] = (!array_key_exists("update_time", $params) || $params['update_time'] == "") ? date("Y-m-d H:i:s", time()) : date("Y-m-d H:i:s", strtotime($params['update_time']));
                    $params['create_time'] = (!array_key_exists("create_time", $params) || $params['create_time'] == "") ? date("Y-m-d H:i:s", time()) : date("Y-m-d H:i:s", strtotime($params['create_time']));
                    // 从 Session 写入 city_id / school_id
                    if (isset($_SESSION['think']['admin']['city_id']) && !empty($_SESSION['think']['admin']['city_id'])) {
                        $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                    }
                    if (isset($_SESSION['think']['admin']['school_id']) && !empty($_SESSION['think']['admin']['school_id'])) {
                        $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                    }
                    $params['status'] = 1;

                    // 设置创建者ID（如果字段存在）
                    ColumnHelper::setColumnUserId($params, $user['id']);

                    // 如果不是超级管理员或城市管理员，强制设置type为0
                    $userGroupId = $user['group_id'] ?? 0;
                    if (!in_array($userGroupId, [1, 2])) {
                        $params['type'] = 0;
                    }

                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success('添加成功');
                    } else {
                        $this->error($this->model->getError() ?: '添加失败');
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        // 传递用户权限信息到前端
        $userGroupId = $user['group_id'] ?? 0;
        $canEditType = in_array($userGroupId, [1, 2]); // 超级管理员或城市管理员
        $this->assignconfig('canEditType', $canEditType);

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $user = $this->auth->getUserInfo();
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }

                    // 权限检查：基于数据所有权和用户组的权限控制
                    $userGroupId = $user['group_id'] ?? 0;
                    $userId = $user['id'] ?? 0;
                    $isOwner = ColumnHelper::isColumnOwner($row, $userId); // 是否是栏目创建者
                    $canEditType = in_array($userGroupId, [1, 2]) || $isOwner; // 超级管理员、城市管理员或创建者

                    // type字段权限检查
                    if (isset($params['type'])) {
                        // 如果是自己创建的栏目，可以修改type字段
                        if ($isOwner) {
                            // 创建者可以修改自己栏目的type字段
                        }
                        // 如果不是自己创建的栏目，需要检查用户组权限
                        else if (!in_array($userGroupId, [1, 2])) {
                            // 保持原有的type值
                            $params['type'] = $row['type'];
                            if ($params['type'] != $row['type']) {
                                $this->error('您只能修改自己创建的栏目的固定状态，或者需要超级管理员/城市管理员权限');
                            }
                        }
                    }

                    $params['update_time'] = (!array_key_exists("update_time", $params) || $params['update_time'] == "") ? date("Y-m-d H:i:s", time()) : date("Y-m-d H:i:s", strtotime($params['update_time']));
                    $params['create_time'] = (!array_key_exists("create_time", $params) || $params['create_time'] == "") ? date("Y-m-d H:i:s", time()) : date("Y-m-d H:i:s", strtotime($params['create_time']));
                    // 从 Session 写入 city_id / school_id（确保编辑时也有值）
                    if (isset($_SESSION['think']['admin']['city_id']) && !empty($_SESSION['think']['admin']['city_id'])) {
                        $params['city_id'] = $_SESSION['think']['admin']['city_id'];
                    }
                    if (isset($_SESSION['think']['admin']['school_id']) && !empty($_SESSION['think']['admin']['school_id'])) {
                        $params['school_id'] = $_SESSION['think']['admin']['school_id'];
                    }
                    $params['status'] = 1;

                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success('编辑成功');
                    } else {
                        $this->error($row->getError() ?: '编辑失败');
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        // 传递用户权限信息到前端
        $userGroupId = $user['group_id'] ?? 0;
        $canEditType = in_array($userGroupId, [1, 2]); // 超级管理员或城市管理员
        $this->assignconfig('canEditType', $canEditType);

        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row = $this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lists($ids = NULL)
    {
        $where = "where 1=1";
        $page = 1;
        $pagesize = 50;

        // 添加type=1的过滤条件
        //        $where .= " and type=1 or (1=1 ";
        $where .= " and type=1 ";

        // 社区管理员权限控制：只能看到"社区信息"栏目
        if (isset($_SESSION['think']['admin']['group_id']) && $_SESSION['think']['admin']['group_id'] == 8) {
            $where .= " and `column` = '社区信息'";
        }

        // 添加school_id过滤条件（如果传递了school参数）
        //        $school_id = $this->request->request('school');
        //        if ($school_id) {
        //            $where .= " and school_id='{$school_id}'";
        //        }
        //        $where .= ")";
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10000 : $pagesize;
                if ($keyValue != "") {
                    $nn = preg_split("/\,/", $keyValue);
                    $where .= " and (1=0";
                    for ($i = 0; $i < count($nn); $i++) {
                        $where .= " or $keyField='{$nn[$i]}'";
                    }
                    $where .= ")";
                }
            }
        }
        // 获取所有数据用于构建树形结构
        $sql = "select id,pid,`column` as name,weigh from dev002_gxyusheng.fa_column $where order by weigh desc,id asc";
        //echo $sql;
        $list = db()->query($sql);

        // 使用Tree类构建树形结构
        $tree = \fast\Tree::instance();
        $tree->init($list, 'pid');
        $list = $tree->getTreeList($tree->getTreeArray(0), 'name');

        // 为树形结构添加层级符号
        foreach ($list as $index => &$item) {
            $level = substr_count($item['name'], chr(8));
            $symbol = '';
            if ($level > 0) {
                // 移除原有的层级标记
                $item['name'] = str_replace(chr(8), '', $item['name']);
                // 添加树形符号
                for ($i = 0; $i < $level; $i++) {
                    if ($i == $level - 1) {
                        $symbol .= '├── ';
                    } else {
                        $symbol .= '│   ';
                    }
                }
                $item['name'] = $symbol . $item['name'];
            }
        }

        // 分页处理
        $pagesize = 10000;
        $total = count($list);
        $start = ($page - 1) * $pagesize;
        $list = array_slice($list, $start, $pagesize);

        echo json_encode(array("list" => $list, "total" => $total));
        exit;
    }

    function del($ids = null)
    {
        $ids = $this->request->param('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }

        $user = $this->auth->getUserInfo();
        $userGroupId = $user['group_id'] ?? 0;
        $userId = $user['id'] ?? 0;

        // 获取要删除的栏目信息
        $columns = $this->model->where('id', 'in', $ids)->select();

        foreach ($columns as $column) {
            // 如果是用户自己创建的栏目，可以删除
            if (ColumnHelper::isColumnOwner($column, $userId)) {
                continue;
            }

            // 如果不是自己创建的固定栏目，需要检查权限
            if ($column['type'] == 1) {
                // 只有超级管理员和城市管理员可以删除其他人创建的固定栏目
                if (!in_array($userGroupId, [1, 2])) {
                    $this->error('选中的记录中包含其他人创建的固定栏目，只有超级管理员和城市管理员才能删除!');
                }
            }
            // 普通栏目所有人都可以删除
        }

        try {
            // 物理删除
            $deleteResult = $this->model->where('id', 'in', $ids)->delete();

            if ($deleteResult) {
                // 删除成功
                $this->success('删除成功!', null, ['refresh' => true]);
            } else {
                // 没有记录被删除
                $this->error('删除失败，没有记录被删除!');
            }
        } catch (Exception $e) {
            // 删除异常
            $this->error('删除失败: ' . $e->getMessage());
        }
    }

    /**
     * 根据pid获取栏目列表
     * @param int $pid 父级ID
     * @return \think\response\Json
     */
    public function getcolumns()
    {
        $pid = $this->request->param('pid', 0);

        try {
            // 查询指定pid下的栏目数据
            $list = $this->model
                ->where('pid', $pid)
                ->field('id,column,pid,weigh')
                ->order('weigh desc,id asc')
                ->select();

            // 转换为数组格式
            $result = [];
            foreach ($list as $item) {
                $result[] = [
                    'id' => $item['id'],
                    'column' => $item['column'],
                    'pid' => $item['pid'],
                    'weigh' => $item['weigh']
                ];
            }

            return json([
                'code' => 1,
                'msg' => 'success',
                'data' => $result,
                'count' => count($result)
            ]);
        } catch (Exception $e) {
            return json([
                'code' => 0,
                'msg' => '获取数据失败：' . $e->getMessage(),
                'data' => [],
                'count' => 0
            ]);
        }
    }
}
